
import 'package:flutter/material.dart';

class SearchTextFiled extends StatefulWidget {
  final bool? enable;
  final String? defaultText;
  final ValueChanged<String>? onChangeText;
  final Function()? spaecktap;
  const SearchTextFiled({super.key, this.enable = true, this.defaultText, this.onChangeText, this.spaecktap});

  @override
  State<SearchTextFiled> createState() => _SearchTextFiledState();
}

class _SearchTextFiledState extends State<SearchTextFiled> {
  final TextEditingController _textEditingController = TextEditingController();
  bool? showClear;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _textEditingController.text = widget.defaultText ?? "";

  }
  @override
  Widget build(BuildContext context) {
    return Container(
        height: 30,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18),
          color: Color(int.parse('0xffEDEDED')),
        ),
        child: Row(
          children: [
            GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 5, 0, 5),
                child: Icon(
                  Icons.search,
                  size: 20,
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                child:  TextField(
                  enabled: widget.enable,
                  autofocus: true,
                  maxLines: 1,
                  style: TextStyle(
                    fontSize: 15,
                  ),
                  controller: _textEditingController,
                  onChanged: _textChange,
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.only(left: 5,right: 5,bottom: 16)

                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: showClear ?? false ? _clearTap : widget.spaecktap,
              child: Container(
                padding: EdgeInsets.fromLTRB(0, 5, 10, 5),
                child: Icon(
                  showClear ?? false ? Icons.clear : Icons.mic,
                  size: 20,
                  color:showClear ?? false  || !widget.enable! ?? false ? Colors.black : Colors.blue,
                ),
              ),
            ),

          ],
        )
    );
  }


  _clearTap(){
    setState(() {
      _textEditingController.clear();
    });
    _textChange('');
  }


  _textChange(String text){
    if(text.length > 0){
      setState(() {
         showClear = true;
      });
    }else {
      setState(() {
        showClear = false;
      });
    }
    if(widget.onChangeText != null){
       widget.onChangeText!(text);
    }
    }


  // _wrapTap(Widget? child, void Function()? cllback){
  //    return GestureDetector(
  //      child: child,
  //      onTap: cllback,
  //    );
  // }
}
